package jsyf.oa.service.report.reportCommon;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.facade.report.reportCommon.BaiDuMapAPIFacade;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by jjx on 2018/5/14.
 */
@Service
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class BaiDuMapAPI implements BaiDuMapAPIFacade {

    /**
     * 通过经纬度获取距离(单位：米)
     * <p>
     * https://api.map.baidu.com/routematrix/v2/walking?output=json&origins=38.84124647,100.82616536&destinations=38.92687744140625,100.46052978515625&ak=PRiE4PRTzpiQUY4GrkwIDKLg2DYcfc5u&tactics=11
     *
     * @return {"status":0,"result":[{"distance":{"text":"38.9公里","value":38911},"duration":{"text":"9.3小时","value":33347}}],"message":"成功"}
     */
    @Override
    public JSONObject getDistanceByLatAndLng(String json) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(json, JSONObject.class);
        JSONObject jsonObject = new JSONObject();

        if (StringUtils.isBlank(jsonParams.getString("lat1")) || StringUtils.isBlank(jsonParams.getString("lng1"))
                || StringUtils.isBlank(jsonParams.getString("lat2"))  || StringUtils.isBlank(jsonParams.getString("lng2")) ) {
            jsonObject.put("distance", "0");
            return jsonObject;
        }
        double lat1 = jsonParams.getDouble("lat1");
        double lng1 = jsonParams.getDouble("lng1");
        double lat2 = jsonParams.getDouble("lat2");
        double lng2 = jsonParams.getDouble("lng2");
        StringBuffer sb = new StringBuffer();
        sb.append("http://api.map.baidu.com/routematrix/v2/riding?");
        sb.append("output=json" + "&");
        sb.append("origins=" + lat1 + "," + lng1 + "&");
        sb.append("destinations=" + lat2 + "," + lng2 + "&");
        sb.append("ak=PRiE4PRTzpiQUY4GrkwIDKLg2DYcfc5u" + "&");
        sb.append("tactics=13");
        JSONObject urlJSON = HttpUtil.request(sb.toString(), "GET", null);
        if (urlJSON != null) {
            jsonParams = FastJsonConvert.convertJSONToObject(urlJSON, JSONObject.class);
            if (jsonParams.getString("status").equals("0")) {
                List<JSONObject> jsonList = FastJsonConvert.convertJSONToArray(jsonParams.getString("result"), JSONObject.class);
                jsonObject.put("distance", FastJsonConvert.convertJSONToObject(jsonList.get(0).getString("distance"), JSONObject.class).getString("text"));
                return jsonObject;
            }
        }
        jsonObject.put("distance", "0");
        return jsonObject;

    }

}
